import uuid
from flask import render_template, Blueprint, jsonify, request, redirect, url_for, session
from sqlalchemy import func
from werkzeug.security import generate_password_hash, check_password_hash

from App.ext import db
from App.models import MainShop, Goods, MainWheel, MainNav, MainHotGoods, MainShow, FoodType, UserModel, CarModel

# Main, MainWheel, MainNav, MainHotGoods, MainShop, MainShow, FoodType, Goods,
# UserModel, CarModel,OrderModel, OrderGoodsModel, UserTicketModel
from App.view_helper import hash_str, send_email_activate
from App.views_constant import ALL_TYPE, ORDER_TOTAL, ORDER_SALE_DESC, ORDER_PRICE_DESC, ORDER_PRICE_ASC, \
    ORDER_SALE_ASC, HTTP_USER_EXIST, HTTP_OK

main = Blueprint('app', __name__)


@main.route('/', methods=['GET', 'POST'])
def hello_world():
    return render_template('user/user_register.html')


# @main.route('/create_models')
# def create_models():
#     """建立 Models数据表"""
#     from App.ext import db
#     from App.models import Main, MainWheel, MainNav, MainHotGoods, MainShop, MainShow, FoodType, Goods, UserModel, \
#         CarModel, OrderModel, OrderGoodsModel, UserTicketModel
#     # db.init_app(app)
#     db.create_all()
#     return "Models 数据创建完成！"


@main.route('/home')
def home():
    main_wheels = MainWheel.query.all()
    main_navs = MainNav.query.all()
    main_mustbuys = MainHotGoods.query.all()
    main_shops = MainShop.query.all()
    main_shop0_1 = main_shops[0:1]
    main_shop1_3 = main_shops[1: 3]
    main_shop3_7 = main_shops[3: 7]
    main_shop7_11 = main_shops[7: 11]
    main_shows = MainShow.query.all()
    data = {
        'title': '首页',
        "main_wheels": main_wheels,
        'main_navs': main_navs,
        'main_mustbuys': main_mustbuys,
        'main_shop0_1': main_shop0_1,
        'main_shop1_3': main_shop1_3,
        'main_shop3_7': main_shop3_7,
        'main_shop7_11': main_shop7_11,
        'main_shows': main_shows,
    }
    return render_template('home.html', context=data)


@main.route('/marketwithparas/')
def marketwithparas():
    typeid = request.args.get('typeid', '104749')
    childcid = request.args.get('childcid', '0')
    order = request.args.get('order', '0')

    if childcid != ALL_TYPE:
        goods_list = Goods.query.filter_by(categoryid=typeid, childcid=childcid)
    else:
        goods_list = Goods.query.filter_by(categoryid=typeid)
    if order == ORDER_TOTAL:
        goods_list = goods_list.order_by('id').limit(50)
    elif order == ORDER_SALE_ASC:
        goods_list = goods_list.order_by(Goods.productnum).limit(50)
    elif order == ORDER_SALE_DESC:
        goods_list = goods_list.order_by(Goods.productnum.desc()).limit(50)
    elif order == ORDER_PRICE_DESC:
        goods_list = goods_list.order_by(Goods.price.desc()).limit(50)
    elif order == ORDER_PRICE_ASC:
        goods_list = goods_list.order_by('price').limit(50)
    order_list = [
        ['综合排序', ORDER_TOTAL],
        ['销量升序', ORDER_SALE_ASC],
        ['销量降序', ORDER_SALE_DESC],
        ['价格升序', ORDER_PRICE_ASC],
        ['价格降序', ORDER_PRICE_DESC],
    ]
    foodtypes = FoodType.query.all()
    childtypenames = FoodType.query.filter_by(typeid=typeid)[0].childtypenames
    childtypelist = childtypenames.split('#')
    childtypenamelist = []
    for val in childtypelist:
        mylist = val.split(':')
        childtypenamelist.append(mylist)

    # 取用户购物车商品数量
    user_id = session.get('user_id', '')
    if user_id:
        carts = CarModel.query.filter_by(user_id=user_id).all()
    else:
        carts = ''
    data = {
        "title": '闪购',
        "foodtypes": foodtypes,
        "goods_list": goods_list,
        'childtypenames': childtypenamelist,
        'order_list': order_list,
        'typeid': typeid,
        'childcid': childcid,
        'order': order,
        'carts': carts,
    }
    return render_template('market.html', context=data)


@main.route('/market/')
def market():
    return redirect(url_for('app.marketwithparas', typeid=104749, childcid='0', order='0'))
    # foodtypes = FoodType.query.all()
    # goods_list = Goods.query.filter_by(categoryid=104749)
    # childtypenamelist = ['全部分类', '0']
    # data = {
    #     "title": '闪购',
    #     "foodtypes": foodtypes,
    #     "goods_list": goods_list,
    #     'childtypenames': childtypenamelist,
    # }
    # return render_template('market.html', context=data)


@main.route('/mine/')
def mine():
    user_id = session.get('user_id', '')
    data = {
        "title": '我的',
        'is_login': False,
    }
    if user_id:
        user = UserModel.query.get(user_id)
        data['username'] = user.username
        data['is_login'] = True

    return render_template('mine.html', context=data)


@main.route('/register/', methods=['GET', 'POST'])
def register():
    if request.method == "GET":
        data = {"title": "注册"}
        return render_template('user/user_register.html', context=data)
    if request.method == "POST":
        name = request.form.get("username")
        password = request.form.get("password")
        password = generate_password_hash(password)  # hash_str(password)  # view_helper 定义hash_str() 函数加密
        email = request.form.get("email")
        icon = request.files.get('icon')
        user = UserModel(username=name, password=password, email=email)
        user.save()
        u_token = uuid.uuid4().hex  # 生成激活验证都uuid
        # cache 存储u_token 给激活验证使用
        #  异步发送激活 email
        # send_email_activate(name, email, u_token)

        return redirect(url_for("app.mine"))


@main.route('/login/', methods=["GET", "POST"])
def login():
    if request.method == "GET":
        data = {"title": "登录"}

    if request.method == "POST":
        name = request.form.get("username")
        password = request.form.get("password")
        user = UserModel.query.filter_by(username=name).first()  # 无查询到记录会返回 None
        if user:
            if check_password_hash(user.password, password):
                session['user_id'] = user.id
                return redirect(url_for("app.mine", context={'title': '登录成功'}))
            else:
                return render_template('user/user_login.html', context={'title': '密码错误'})
        data = {"title": "用户名错误"}
    return render_template('user/user_login.html', context=data)


@main.route('/logout/')
def logout():
    session.pop('user_id')
    return redirect(url_for('app.mine'))


@main.route('/checkuser/')
def check_user():
    form_username = request.args.get("username")
    print(form_username)
    count = UserModel.query.filter_by(username=form_username).count()
    if count:
        data = {"status": HTTP_USER_EXIST, 'desc': '用户名已存在！'}
    else:
        data = {"status": HTTP_OK, 'desc': 'ok'}
    return jsonify(data)


@main.route('/goods')
def goods():
    '''测试数字转字典'''
    goodses = MainWheel.query.limit(5).all()
    return jsonify([goods.to_dict() for goods in goodses])


@main.route('/cart/')
def cart():
    user_id = session.get('user_id', '')
    if user_id:
        carts = CarModel.query.filter_by(user_id=user_id).all()
        # 判断是否存在未选择的商品
        carts1 = CarModel.query.filter_by(user_id=user_id, is_select=True).all()
        result = 0
        for cart in carts1:
            result = cart.goods.price * cart.c_num + result
        from sqlalchemy.sql import exists
        is_all_select = db.session.query(exists().where(CarModel.is_select == 0)).scalar()
        # print(is_all_select)
        data = {
            'carts': carts,
            'is_all_select': not is_all_select,
            'result': round(result, 2),
        }
        return render_template('cart.html', context=data)
    else:
        return redirect(url_for("app.login"))


@main.route('/allselect/')
def all_select():
    user_id = session.get('user_id', '')  # 判断是否登录用
    selects = request.args.get('selects').split('#')
    carts = CarModel.query.filter(CarModel.id.in_(selects))
    action = request.args.get('action')
    for cart in carts:
        cart.is_select = not cart.is_select
        cart.save()
    carts = CarModel.query.filter_by(user_id=user_id, is_select=True).all()
    result = 0
    for cart1 in carts:
        result = cart1.goods.price * cart1.c_num + result
    data = {
        'status': 200,
        'msg': 'all ok',
        'result': round(result, 2)
    }
    return jsonify(data)


@main.route('/changecartstatus/')
def change_cart_status():
    user_id = session.get('user_id', '')
    if user_id:
        cart_id = request.args.get('cart_id', '')
        cart = CarModel.query.get(cart_id)
        # 需判断该id是否本用户的
        if cart_id and user_id == cart.user_id:
            cart.is_select = not cart.is_select
            cart.save()
            carts = CarModel.query.filter_by(user_id=user_id, is_select=True).all()
            result = 0
            for cart1 in carts:
                result = cart1.goods.price * cart1.c_num + result
            from sqlalchemy.sql import exists
            is_all_select = db.session.query(exists().where(CarModel.is_select == 0)).scalar()
            data = {
                'status': 200,
                'msg': 'status is change!',
                'check': cart.is_select,
                'is_all_select': not is_all_select,
                'result': round(result, 2),
            }
        else:
            data = {
                'status': 901,
                'msg': 'error,无此订单！'
            }
        return jsonify(data)

    else:
        data = {
            'status': 902,
            'msg': 'error,用户未登录！'
        }
        return jsonify(data)


@main.route('/subcart/')
def sub_cart():
    '''减少购物车商品数量'''
    user_id = session.get('user_id', '')
    if user_id:
        cart_id = request.args.get('cart_id', '')
        cart = CarModel.query.get(cart_id)
        # 需判断该id是否本用户的
        if cart_id and user_id == cart.user_id:
            if cart.c_num > 1:
                cart.c_num = cart.c_num - 1
                cart.save()
                carts = CarModel.query.filter_by(user_id=user_id, is_select=True).all()
                result = 0
                for cart1 in carts:
                    result = cart1.goods.price * cart1.c_num + result
                data = {
                    'status': 200,
                    'msg': 'sub is ok!',
                    'c_num': cart.c_num,
                    'result': round(result, 2),
                }
            else:
                cart.delete()
                data = {
                    'status': 903,
                    'msg': 'is 0!',
                }
        else:
            data = {
                'status': 901,
                'msg': 'error,无此订单！'
            }
    else:
        data = {
            'status': 902,
            'msg': 'error,用户未登录！'
        }
    return jsonify(data)


@main.route('/addcart/')
def add_cart():
    '''增加购物车商品数量'''
    user_id = session.get('user_id', '')
    if user_id:
        cart_id = request.args.get('cart_id', '')
        cart = CarModel.query.get(cart_id)
        # 需判断该id是否本用户的
        if cart_id and user_id == cart.user_id:
            if cart.c_num < 99:
                cart.c_num = cart.c_num + 1
                cart.save()
                carts = CarModel.query.filter_by(user_id=user_id, is_select=True).all()
                result = 0
                for cart1 in carts:
                    result = cart1.goods.price * cart1.c_num + result
                data = {
                    'status': 200,
                    'msg': 'add is ok!',
                    'c_num': cart.c_num,
                    'result': round(result, 2),
                }
            else:
                data = {
                    'status': 200,
                    'msg': '99 not add!',
                    'c_num': cart.c_num,
                }
        else:
            data = {
                'status': 901,
                'msg': 'error,无此订单！'
            }
    else:
        data = {
            'status': 902,
            'msg': 'error,用户未登录！'
        }
    return jsonify(data)


@main.route('/addtocart/')
def add_to_cart():
    '''闪够货品到购物车'''
    goodsid = request.args.get('goodsid', '')
    # 这里判断Goods是否存在
    user_id = session.get('user_id', '')
    if user_id:
        cart_obj = CarModel.query.filter_by(user_id=user_id).filter_by(goods_id=goodsid).first()
        if cart_obj:
            if cart_obj.c_num < 99:
                cart_obj.c_num = cart_obj.c_num + 1
        else:
            cart_obj = CarModel()
            cart_obj.goods_id = goodsid
            cart_obj.user_id = user_id

        cart_obj.save()

        data = {
            'status': 200,
            'msg': 'goods add success',
            'goodsid': goodsid,
            'c_num': cart_obj.c_num
        }
    else:
        data = {
            'status': 901,
            'msg': '用户未登录！'
        }
    return jsonify(data)


@main.route('/subtocart/')
def sub_to_cart():
    goodsid = request.args.get('goodsid', '')
    # 这里判断Goods是否存在
    user_id = session.get('user_id', '')
    if user_id:
        cart_obj = CarModel.query.filter_by(user_id=user_id).filter_by(goods_id=goodsid).first()
        if cart_obj:
            if cart_obj.c_num <= 1:
                # db.session.delete(cart_obj)
                # db.session.commit()
                cart_obj.delete()
            else:
                cart_obj.c_num = cart_obj.c_num - 1
                cart_obj.save()

            data = {
                'status': 200,
                'msg': 'goods add success',
                'goodsid': goodsid,
                'c_num': cart_obj.c_num
            }
        else:
            data = {
                'status': 902,
                'msg': '请先添加商品'
            }
    else:
        data = {
            'status': 901,
            'msg': '用户未登录！'
        }
    return jsonify(data)
